package pl.edu.agh.uddiProxy.server;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;

import org.gwtwidgets.server.spring.GWTSpringController;

import pl.edu.agh.uddiProxy.client.Application;
import pl.edu.agh.uddiProxy.client.Currency;
import pl.edu.agh.uddiProxy.client.CurrencyService;
import pl.edu.agh.uddiProxy.dao.DAOHelper;

public class CurrencyServiceImpl extends GWTSpringController implements CurrencyService {
	private static final long serialVersionUID = 184898055438107533L;
	
	private static CurrencyConverter converter;
	
	public List<Currency> getAllCurrency() {
		return new ArrayList<Currency>(converter.getAllCurrency());
	}

	@Override
	public void setServletContext(ServletContext servletContext) {
		try {
			converter = new CurrencyConverter(servletContext.getRealPath("WEB-INF/classes/currency.csv"));
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		}
	}

	public Double convert(String modelKey, String targetCurrency) {
		String value = DAOHelper.getDynamicParameterDAO().getByTModel(modelKey).getParameterValue(Application.PRICE_PARAMETER).getValue();
		String currency = DAOHelper.getParametersMap().getParametersMap().get(Application.PRICE_PARAMETER).getUnit();
		try {
			return new Double(converter.convert(currency, targetCurrency, value));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}

	public Double convert(Double value, String sourceCurrency) {
		String currency = DAOHelper.getParametersMap().getParametersMap().get(Application.PRICE_PARAMETER).getUnit();
		try {
			return new Double(converter.convert(sourceCurrency, currency, value.toString()));
		} catch (IOException e) {
			e.printStackTrace();
		}
		return null;
	}
	
}
